package cn.shengchao.job;

/**
 * @program: examstarapi
 * @description: 用户信息收集
 * @author: Xiong weiqiang
 * @create: 2025-04-14 14:20
 */

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.shengchao.base.event.userinfo.UserInfoBatchCollectEvent;
import cn.shengchao.base.event.userinfo.UserInfoSingleCollectEvent;
import cn.shengchao.base.event.userinfo.UserInfoCollectType;
import cn.shengchao.examstar.me.collect.acl.adapters.repositories.UserCollectInfoRepository;
import cn.shengchao.examstar.me.infrastructure.dao.po.UserCollectInfo;
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.model.ExecuteResult;
import com.aizuda.snailjob.common.log.SnailJobLog;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

@Component
public class UserCollectInfoJob {
    @Autowired
    private UserCollectInfoRepository userCollectInfoRepository;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    /**
     * method : jobExecute
     * description :     用户信息采集的定时任务
     * @param jobArgs \{@link JobArgs \}
     * @return : com.aizuda.snailjob.client.model.ExecuteResult
     * @author : Xiong weiqiang
     * @CreateDate : 2025-04-14 14:24:29
     *
     * @Reviewed :
     * @UpdateLog :    Name    Date    Reason/Contents
     *             ---------------------------------------
     *                ****    ****    ****
     *
     */
    @JobExecutor(name = "UserInfoCollectNewJob")
    public ExecuteResult userInfoCollectNewJob(JobArgs jobArgs) {
        SnailJobLog.REMOTE.info("开始执行用户信息任务-新用户初始化"+ DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        // 调用新增接口
        List<Long> list = userCollectInfoRepository.selectNotCollectUserIdList();
        if (CollUtil.isNotEmpty(list)) {
            List<UserCollectInfo> userCollectInfos=new ArrayList<>();
            for (Long userId : list) {
                UserCollectInfo userCollectInfo = new UserCollectInfo();
                userCollectInfo.setUserId(userId);
                userCollectInfo.setGender(0);
                userCollectInfo.setVipLevel(0);
                userCollectInfo.setVipScore(0);
                userCollectInfo.setGradeLevel(0);
                userCollectInfo.setTags(new HashSet<>());
                userCollectInfo.setLastUpdateTime(new Date());
                userCollectInfos.add(userCollectInfo);
            }
            userCollectInfoRepository.saveOrUpdateBatch(userCollectInfos);
            userCollectInfos.forEach(userCollectInfo ->applicationEventPublisher.publishEvent(new UserInfoSingleCollectEvent(this,userCollectInfo.getUserId(),UserInfoCollectType.COLLECT_USER_BASE_INFO)));
        }
        SnailJobLog.REMOTE.info("开始执行用户信息任务-新用户初始化完成：新增用户"+(CollUtil.isNotEmpty(list)?list.size():0)+"个");
        return ExecuteResult.success();
    }
    @JobExecutor(name = "UserInfoCollectUpdateJob")
    public ExecuteResult userInfoCollectUpdateJob(JobArgs jobArgs) {
        int userNumber=0;
        long startTime = System.currentTimeMillis();
        SnailJobLog.REMOTE.info("开始执行用户信息任务-用户定时更新"+ DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        while (true){
            List<Long> list = userCollectInfoRepository.selectExistUserIdListByUpdateAsc(100);
            if (CollUtil.isEmpty(list)){
                break;
            }else {
                //先把最后更新时间更掉，不然循环就有问题了
                userCollectInfoRepository.update(Wrappers.lambdaUpdate(UserCollectInfo.class).set(UserCollectInfo::getLastUpdateTime,new Date()).in(UserCollectInfo::getUserId,list));
                userNumber+=list.size();
                applicationEventPublisher.publishEvent(new UserInfoBatchCollectEvent(this,list, UserInfoCollectType.COLLECT_USER_BASE_INFO));
                applicationEventPublisher.publishEvent(new UserInfoBatchCollectEvent(this,list, UserInfoCollectType.COLLECT_USER_VIP_INFO));
            }
        }
        long endTime = System.currentTimeMillis();
        SnailJobLog.REMOTE.info("执行用户信息任务-用户定时更新完成：执行用户数"+userNumber+"个"+"，耗时："+(endTime-startTime)+"毫秒");
        return ExecuteResult.success();
    }

}